<?php

namespace App\Http\Controllers;

use App\Grip;
use App\Group;
use Illuminate\Http\Request;
use App\Chest;
use Illuminate\Support\Facades\Auth;
use App\Service\ChestLock;

class ScanController extends Controller
{

    //扫码结果展示页面
    public function index(Request $request)
    {
        $user = Auth::user();
        $chestNumber = '869300038720094';//$request->get('chest_number');
        $chest = Chest::where('chest_number', $chestNumber)->first();
        if (!$chest) {
            return $this->error('柜子编号错误');
        }
        $grips = Grip::where(['chest_id' => $chest['id']])->get();
        if($chest->isUser())
        {
            return view('scan.index', [
                'chest' => $chest,
                'grips'=>$grips
            ]);
        }elseif($chest->isCompany() || $chest->isBuyer())
        {
            return view('scan.company', [
                'chest' => $chest,
                'grips'=>$grips
            ]);
        }else{
            return view('scan.time', [
                'chest' => $chest,
                'grips'=>$grips,
                'user'=>$user
            ]);
        }

    }

    public function scan()
    {
        return view('scan.scan');
    }
    public function bound()
    {
        $user = Auth::user();
        //选择当前用户的格子
        $chestNumber = '869300038720094';//$request->get('chest_number');
        $chest = Chest::where('chest_number', $chestNumber)->first();
        if (!$chest) {
            return $this->error('柜子编号错误');
        }
        $grips = Group::where(['owner_id' => $user->id])->get();
        return view('scan.bound',['grips'=>$grips]);
    }
    public function unbound()
    {
        $chestNumber = '869300038720094';//$request->get('chest_number');
        $chest = Chest::where('chest_number', $chestNumber)->first();
        if (!$chest) {
            return $this->error('柜子编号错误');
        }
        $grips = Grip::where(['chest_id' => $chest['id']])->get();
        return view('scan.unbound', [
            'chest' => $chest,
            'grips'=>$grips
        ]);
    }



    /**
     * 开启柜门
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function open(Request $request)
    {
        $this->validate($request, [
            'chest_number' => 'required'
        ]);

        $chestNumber = $request->get('chest_number');
        $chest = Chest::where('chest_number', $chestNumber)->first();

        if (!$chest) {
            return $this->error('设备编号错误');
        }

        $gripId = $request->get('grip_id');
        $user = Auth::user();
        // 检测用户是否有打开该设备的资格
        $lock = new ChestLock();
        $lock->setChest($chest->id);
        $lock->setGrip($gripId);
        if ($lock->open()) {
            return $this->success('开启成功');
        } else {
            return $this->error('开启失败');
        }


    }
}
